package org.huanmin.common.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.huanminabc.utils_common.requestclient.okhttp.OkHttpUtil;
import lombok.SneakyThrows;
import org.openqa.selenium.Cookie;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class BaiJiaHaoImg {
    @Value("${baijiahao.img-generate}")
    private String imgGenerate;

    @SneakyThrows
    public List<String> getImgList(Set<Cookie> cookies, String keyword) {
        StringBuilder sb = new StringBuilder();
        for (Cookie cookie : cookies) {
            sb.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
        }
        //去掉最后一个分号
        sb.deleteCharAt(sb.length() - 1);
        String apiKey = sb.toString();
        String sync = OkHttpUtil.builder().
                 url(imgGenerate)
                .addHeader("Cookie", "Bearer  " + apiKey)
                .addParam("page_no", 0)
                .addParam("page_size", 20)
                .addParam("keyword", keyword)
                .post("form").sync();

        JSONObject jsonObject = JSON.parseObject(sync);
        if ( jsonObject.get("data")==null){
            return new ArrayList<>();
        }
        String data = jsonObject.get("data").toString();
        JSONObject jsonObject1 = JSON.parseObject(data);
        JSONArray imglist1 = jsonObject1.getJSONArray("imglist");
        List<String> bigThumbUrl = imglist1.stream().limit(3).map(o -> (JSONObject) o).map(o -> o.get("big_thumb_url").toString()).collect(Collectors.toList());
        Thread.sleep(2000);//休息2秒因为接口有限流
        return bigThumbUrl;
    }


}
